class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        int closestSum = nums[0] + nums[1] + nums[2]; // 初始化一个合理值
        int minDiff = abs(closestSum - target);

        for (int i = 0; i < n - 2; ++i)
        {
            int fixedNum = nums[i];
            // 去重：跳过重复的 fixedNum
            if (i > 0 && fixedNum == nums[i - 1])
                continue;

            // 优化一：最小可能和 > target
            int minPossibleSum = fixedNum + nums[i + 1] + nums[i + 2];
            if (minPossibleSum > target)
            {
                if (minPossibleSum - target < minDiff)
                    closestSum = minPossibleSum;
                break; // 后续只会更大，直接退出
            }

            // 优化二：最大可能和 < target
            int maxPossibleSum = fixedNum + nums[n - 2] + nums[n - 1];
            if (maxPossibleSum < target)
            {
                if (target - maxPossibleSum < minDiff)
                {
                    minDiff = target - maxPossibleSum;
                    closestSum = maxPossibleSum;
                }
                continue; // 当前 fixedNum 无法达到 target，尝试下一个
            }

            // 双指针查找
            int left = i + 1, right = n - 1;
            while (left < right)
            {
                int currentSum = fixedNum + nums[left] + nums[right];
                if (currentSum == target)
                    return target; // 找到精确值，直接返回

                int diff = abs(currentSum - target);
                if (diff < minDiff)
                {
                    minDiff = diff;
                    closestSum = currentSum;
                }

                if (currentSum > target) 
                    --right;
                else
                    ++left;
            }
        }
        return closestSum;
    }
};